<template>
	<view class="allImg">
		<AddModel ref="addSet" />
		<view class="handleBtn">
			<button @click="handleUploadImg">上传图片</button>
			{{ cTimer }}
			<button @click="addList">加入作品集合</button>
		</view>
		<view class="uni-pagination-box"><uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total"
				@change="change" /></view>
		<view class="uni-container">
			<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<uni-th width="150" align="center">图片预览</uni-th>
					<uni-th width="150" align="center">是否精选</uni-th>
					<uni-th width="150" align="center">查看次数</uni-th>
					<uni-th align="center">类型</uni-th>
					<uni-th align="center">标签</uni-th>
					<uni-th width="204" align="center">创建时间</uni-th>
					<uni-th width="204" align="center">设置</uni-th>
				</uni-tr>
				<uni-tr v-for="(item) in dataInfo" :key="item._id">
					<uni-td>
						<!-- https://env-00jxt14elvj6.normal.cloudstatic.cn/wallpaper/1716809350282.jpg -->
						<image :src="`https://env-00jxt14elvj6.normal.cloudstatic.cn/${item.path}`" class="tabImg"
							mode="aspectFill" />
					</uni-td>
					<uni-td align="center">{{ item.isSift ? '是' : '否' }}</uni-td>
					<uni-td align="center">
						{{ item.showCount }}
					</uni-td>
					<uni-td align="center">{{ item.type || '其它' }}</uni-td>
					<uni-td align="center">{{ item.tags || '其它' }}</uni-td>
					<uni-td align="center">{{ item.createTime }}</uni-td>
					<uni-td>
						<view class="uni-group">
							<button class="uni-button" size="mini" type="primary">修改</button>
							<button class="uni-button" size="mini" type="warn" @click="delImgRecord(item._id)">删除</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
		</view>
	</view>
</template>

<script>
import {
	dataInfo
} from './tableData.js'
import AddModel from './AddModel.vue'

import {
	connectWallpaperTable,
	connectWallpaperTableTem,
	handleWallpaperTodo
} from '../../utils/uniCloudTodo'
const databaseCode = 'wallpaper'
// const databaseCode = 'wallpaperTem'

export const getTimerFromDate = (timestamp, dateFormat) => {
	const date = new Date(timestamp); // 将时间戳转换为Date对象
	const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
	const map = {
		'YYYY': date.getFullYear(), // 年份
		'MM': date.getMonth() + 1, // 月份
		'DD': date.getDate(), // 日期
		'HH': date.getHours(), // 小时
		'mm': date.getMinutes(), // 分钟
		'ss': date.getSeconds(), // 秒
		'EEEE': days[date.getDay()],
	};

	return dateFormat.replace(/YYYY|MM|DD|HH|mm|ss|EEEE/g, match => {
		return map[match].toString().padStart(2, '0');
	});
}
export default {
	components: {
		AddModel
	},
	data() {
		return {
			searchVal: '',
			dataInfo: [],
			// 每页数据量
			pageSize: 20,
			// 当前页
			pageCurrent: 1,
			// 数据总量
			total: 1000,
			loading: false
		}
	},
	created() {
		this.selectedIndexs = []
		this.getData(1)
	},
	computed: {
		isNotTem() {
			return databaseCode === 'wallpaper'
		},
		cTimer() {
			// return getTimerFromDate(new Date(), 'YYYY-MM-DD')
			return getTimerFromDate(new Date().getTime() + (24 * 60 * 60 * 1000), 'YYYY-MM-DD')
		},
	},
	methods: {
		async addList() {

			let thumbList = []
			let imgList = []
			let previewList = []
			uni.showLoading({
				title: '加载中'
			});
			const saveImgToAlbum = (tempFilePath) => {
				var oA = document.createElement("a");
				oA.download = ''; // 设置下载的文件名，默认是'下载'
				oA.href = tempFilePath; //临时路径再保存到本地
				document.body.appendChild(oA);
				oA.click();
				oA.remove(); // 下载之后把创建的元素删除

			}
			// // 先下载数据
			// for (let index = 0; index < this.imgChoList.length; index++) {
			// 	try {
			// 		const {
			// 			thumb,
			// 			preview,
			// 			img,
			// 			id
			// 		} = this.imgChoList[index];

			// 		const res = await uni.downloadFile({
			// 			url: img,
			// 		})
			// 		console.log('res :>> ', res);
			// 		saveImgToAlbum(res.tempFilePath)
			// 	} catch (error) {

			// 	}
			// }
			const imgChoList = this.selectedIndexs.map(item => this.dataInfo[item])
			console.log('imgChoList', imgChoList)
			for (let index = 0; index < imgChoList.length; index++) {
				try {
					const {
						path
					} = imgChoList[index];
					// const timer = new Date().getTime()
					// const thumbResult = await uniCloud.uploadFile({
					// 	filePath: thumb,
					// 	cloudPath: `outSideImgHis/${id}-${timer}-thumb.png`,
					// });
					// const imgResult = await uniCloud.uploadFile({
					// 	filePath: img,
					// 	cloudPath: `outSideImgHis/${id}-${timer}-img.png`,
					// });
					// const previewResult = await uniCloud.uploadFile({
					// 	filePath: preview,
					// 	cloudPath: `outSideImgHis/${id}-${timer}-preview.png`,
					// });
					// const regExp = new RegExp('cloud://env-00jxt14elvj6/', 'g');
					thumbList.push(path)
					imgList.push(path)
					previewList.push(path)

				} catch (error) {

				}
			}

			let imgInfo = {
				thumb: thumbList,
				img: imgList,
				preview: previewList
			}
			console.log('imgInfo :>> ', imgInfo);
			const db = uniCloud.database()
			const pastDB = db.collection('pastPhotoList')
			const typeInfo = '美女'

			let addInfo = await pastDB.add({
				imgIdInfo: imgInfo,
				type: '美女',
				createTime: this.cTimer,
			})
			uni.hideLoading();
			console.log('addInfo,', addInfo, '添加成功了')





		},

		async delImgRecord(imgId) {
			const that = this
			uni.showModal({
				title: '提示',
				content: '确定要删除照片吗？',
				success: function (res) {
					if (res.confirm) {
						handle()
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
			const handle = async () => {
				const isTemAction = this.isNotTem ? connectWallpaperTable() : connectWallpaperTableTem()
				const {
					result
				} = await isTemAction.doc(imgId).remove()
				console.log('object :>> ', result);
				if (result.errCode === 0) {
					uni.showToast({
						title: '删除成功'
					})
					that.getData()
				} else {
					uni.showToast({
						title: '删除失败',
						icon: 'error',
						duration: 2000
					});
				}
			}
		},
		// 上传文件
		async uploadFiles(filePaths) {
			this.loading = true
			let imageList = []
			for (var i = 0; i < filePaths.length; i++) {
				const item = filePaths[i]
				const uploadTask = await uniCloud.uploadFile({
					filePath: item.filePath,
					cloudPathAsRealPath: true,
					cloudPath: `wallpaper/${item.name}`,
				});
				console.log(uploadTask, 'uploadTask');
				const fileId = uploadTask.fileID.split('/')
				imageList.push(`wallpaper/${fileId[fileId.length - 1]}`)
			}

			function getRandomArbitrary(min, max) {
				return Math.random() * (max - min) + min;
			}

			function getRandomNumber(min, max) {
				return Math.floor(getRandomArbitrary(min, max + 1));
			}
			const {
				isSift,
				tags,
				type
			} = this.$refs.addSet
			handleWallpaperTodo().batchUpload({
				databaseCode,
				imageList: imageList.map(path => {
					return {
						path,
						openid: 'orrOI671HjtuhoW3oCCkh4xNCoQ4',
						userId: 'map[$oid:6644cbe2ce5ec96267e82252]',
						showCount: getRandomNumber(450, 600),
						isSift,
						type,
						tags,
						createTime: new Date().getTime()
					}
				})
			}).then(res => {
				this.getData(1)
			})

		},
		handleUploadImg() {
			const that = this
			uni.chooseImage({
				count: 100,
				success: (res) => {
					const tempFilePaths = res.tempFiles.map(item => {
						return {
							name: item.name,
							filePath: item.path
						}
					})
					that.uploadFiles(tempFilePaths);
				}
			});
		},
		// 多选处理
		selectedItems() {
			return this.selectedIndexs.map(i => this.dataInfo[i])
		},
		// 多选
		selectionChange(e) {
			this.selectedIndexs = e.detail.index
		},
		//批量删除
		delTable() {
			console.log(this.selectedItems())
		},
		// 分页触发
		change(e) {
			this.$refs.table.clearSelection()
			this.selectedIndexs.length = 0
			console.log(e);
			this.pageCurrent = e.current
			this.getData(e.current)
		},
		// 搜索
		search() {
			this.getData(1, this.searchVal)
		},
		// 获取数据
		getData(pageCurrent = this.pageCurrent, value = '') {
			this.loading = true
			this.pageCurrent = pageCurrent
			uni.showLoading({
				title: '加载中...'
			})

			uniCloud.database().collection(databaseCode)
				.skip((this.pageCurrent - 1) * this.pageSize) //跳过已经查询的记录数量
				.limit(this.pageSize) //每次请求10条记录
				.where({}) //只查询自己的订单
				.get()
				.then(res => {
					this.dataInfo = this.dataInfo.concat(res.result.data)
					this.loading = false
				})
				.catch(err => {
					console.log('查询失败', err)
				})
				.finally(() => {
					//无论成功或失败都执行
					uni.hideLoading()
				})

		},

	}
}
</script>

<style>
.allImg {
	height: 500px;
	width: 100%;
}

.uni-container {
	height: 500px;
}

/* #ifndef H5 */
/* page {
	padding-top: 85px;
} */
/* #endif */
.uni-group {
	display: flex;
	align-items: center;
}
</style>